package crp.core.security.domain.services;

import crp.core.security.domain.models.AccessToken;
import crp.core.security.domain.models.SSOAuthenticationRequest;
import crp.core.security.domain.services.token.AccessTokenBuilder;
import io.quarkus.security.identity.IdentityProviderManager;
import io.quarkus.security.identity.SecurityIdentity;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.Map;

@ApplicationScoped
public class SSOAuthenticator {
    private final IdentityProviderManager identityProviderManager;
    private final AccessTokenBuilder accessTokenBuilder;

    @Inject
    public SSOAuthenticator(IdentityProviderManager identityProviderManager,
                            AccessTokenBuilder accessTokenBuilder) {
        this.identityProviderManager = identityProviderManager;
        this.accessTokenBuilder = accessTokenBuilder;
    }

    public AccessToken authenticate(String provider, Map<String, Object> attributes) {
        var request = SSOAuthenticationRequest.builder()
                .provider(provider)
                .attributes(attributes)
                .build();
        SecurityIdentity securityIdentity = identityProviderManager.authenticateBlocking(request);
        return accessTokenBuilder.create(securityIdentity);
    }
}
